package com.laiyizhan.common.interceptor;

import com.laiyizhan.common.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局拦截器
 * Created by folie
 */
public class GlobalInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
         * 打印请求url, param, ip, ua信息
         */
        String url = request.getServletPath();
        String method = request.getMethod();
        String ip = request.getRemoteAddr();
        String ua = request.getHeader("User-Agent");
        Enumeration parameterNames = request.getParameterNames();
        Map<String, Object> queryMap = new HashMap<>();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            String value = request.getParameter(name);
            queryMap.put(name, value);
        }
        logger.info("url = {}, method={}, query = {}, ip = {}, ua = {}", url, method, JsonUtil.toJson(queryMap), ip, ua);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}